import React, { Component } from 'react'

import Child from './Child'
import Child2 from './Child2'

class Index extends Component {
  // state = {
  //   count: 0
  // }

  // 初始化钩子
  constructor() {
    super()
    this.state = {
      count: 0,
      width: '100px',
      color: 'red',
      obj: {
        x: 100
      }
    }

    // console.log('constructor')
  }

  // 挂载期钩子
  // UNSAFE_componentWillMount() {
  //   // console.log('componentWillMount')
  // }

  handleClick = () => {
    this.state.obj = {
      ...this.state.obj,
      y: 200
    }
    this.setState({
      count: 0
    })
  }

  handleChangeColor = () => {
    this.setState({
      color: 'green'
    })
  }

  handleChangeWidth = () => {
    this.setState({
      width: '200px'
    })
  }

  getSnapshotBeforeUpdate() {
    const width = document.querySelector('#div').getBoundingClientRect().width
    return width
  }

  // 第一次渲染页面
  render() {
    // console.log('render')

    return (
      <>
        <div>
          lifetimes
          {/* <button onClick={this.handleClick}>change count</button>
          <Child 
            count={this.state.count}
            obj={this.state.obj}
          ></Child> */}
          <button onClick={this.handleClick}>change count</button>
          <button onClick={this.handleChangeColor}>change color</button>
          <Child2 count={this.state.count} color={this.state.color}></Child2>
        
        </div>
        <div id="div" style={{width: this.state.width, height: '100px', background: 'red'}}></div>
        <button onClick={this.handleChangeWidth}>change width</button>
      </>
    )
  }

  // 第一次渲染完毕
  componentDidMount() {
    // console.log('componentDidMount')

    setTimeout(() => {
      // this.setState({
      //   count: 900
      // })
    }, 2000)
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log(snapshot)
  }
}

export default Index;